<template>
  <div class="count-box">
    <button class="minus" @click="handleCount(-1)">-</button>
    <input type="text" :value="value" @change="handleChange" class="inp">
    <button class="add" @click="handleCount(1)">+</button>
  </div>
</template>

<script>
export default {
  props: {
    value: {
      type: Number,
      default: 1
    }
  },
  methods: {
    handleCount (num) {
      if (this.value <= 1 && num === -1) return
      this.$emit('input', this.value + num)
    },
    handleChange (e) {
      const num = +e.target.value // 转数字处理 成功则为数字 失败为NaN
      if (isNaN(num) || num < 1) {
        e.target.value = this.value
        return
      }
      this.$emit('input', num)
    }
  }
}
</script>

<style lang="less" scoped>
.count-box {
  width: 110px;
  display: flex;
  .add, .minus {
    width: 30px;
    height: 30px;
    outline: none;
    border: none;
    background-color: #efefef;
  }
  .inp {
    width: 40px;
    height: 30px;
    outline: none;
    border: none;
    margin: 0 5px;
    background-color: #efefef;
    text-align: center;
  }
}
</style>
